package org.vnl.platform.impl.openjpa.orm;

import java.sql.Connection;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.vnl.platform.orm.IConnectionManager;

/**
 * 利用JPA實作PDK的ORM機制,此Manager主要負責連上JPA的Persist Unit因此必需要保存Persist Unit Name.
 * 
 * @author Vaughan
 *
 */
public class JPAConnectionManager implements IConnectionManager {

    private String persistUnit;
    
    private static final ThreadLocal<EntityManagerFactory> currentSession = new ThreadLocal<EntityManagerFactory>();
    
    @Override
    public Connection getCurrentConnection() {
        throw new RuntimeException("OpenJPA Connection Manager does not support this type of connection");
    }

    @Override
    public Object getCurrentSession() {
        if (currentSession.get() == null) {
            currentSession.set(Persistence.createEntityManagerFactory(this.persistUnit));
        }
        return currentSession.get();
    }

    public String getPersistUnit() {
        return persistUnit;
    }

    public void setPersistUnit(String persistUnit) {
        this.persistUnit = persistUnit;
    }

}
